<?php

function document_instance_list_page()
{
    @$output = drupal_render(drupal_get_form('document_instance_list_form'));
    return $output;
}

function document_instance_list_page_with_id($template_id)
{
    @$output = drupal_render(drupal_get_form('document_instance_list_form', $template_id));
    return $output;
}


function document_instance_list_form($form, &$form_state)
{
    global $user;

    $template_id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;

    // 模板
    $result = db_select('document_template', 'mt')
                ->fields('mt', array('document_template_id', 'title'))
                ->orderBy('timestamp')
                ->execute();
    $template_options = [];
    foreach ($result as $row) {
        $template_options[] = $row->document_template_id;
    }
    if (!in_array($template_id, $template_options)) {
        drupal_set_message(t('文档模板不存在！'), 'status', FALSE);
        exit;
    }

    $form_state['values']['template_id'] = $template_id;

    // 文档填写人。只能看到自己和下属
    $employee_options[$user->uid] = $user->name;
    $query = db_select('employee', 'e1');
    $query->join('employee', 'e2', 'e2.manager_uid = e1.employee_id');
    $query->condition('e1.employee_id', $user->uid, '=');
    $query->addField('e2', 'employee_id');
    $query->addField('e2', 'employee_name');
    $result = $query->execute();
    foreach ($result as $row) {
        $employee_options[$row->employee_id] = $row->employee_name;
    }

    if (empty($form_state['values']['employee_list'])) {
        $form_state['values']['employee_list'] = $user->uid;
    }

    $form['employee_list'] = array(
        '#type' => 'select',
        '#validated' => TRUE,
        '#required' => TRUE,
        '#options' => $employee_options,
        '#default_value' => $form_state['values']['employee_list'],
    );
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state);
    $form['address'] = _insert_address_selection_form($form, $form_state,'address', 5, FALSE, '');
    $table['#markup'] = data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');

    return $form;
}

function data_list_view_page($form, $form_state)
{
    global $user;
    $output = '';
    $header = array(
        array('data' => '选择', 'class' => ['essential no']),
        array('data' => '地点', 'class' => ['essential address']),
        array('data' => '填写时间', 'class' => ['essential timestamp'], 'field' => 'timestamp'),
        array('data' => '操作', 'class' => ['essential more']),
    );
    $rows = array();

    $query = db_select('document_instance', 'MI')->extend('PagerDefault')->extend('TableSort');
    $query->join('document_template', 'MT', 'MT.document_template_id = MI.document_template_id');
    $query->join('addr', 'A', 'A.addr_id = MI.addr_id');
    $query->leftJoin('addr', 'Province', 'A.province_id=Province.addr_id');
    $query->leftJoin('addr', 'City', 'A.city_id=City.addr_id');
    $query->leftJoin('addr', 'County', 'A.county_id=County.addr_id');
    $query->leftJoin('addr', 'Town', 'A.town_id=Town.addr_id');
    $query->leftJoin('addr', 'Village', 'A.village_id=Village.addr_id');
    $query->addField('Province', 'name', 'province');
    $query->addField('City', 'name', 'city');
    $query->addField('County', 'name', 'county');
    $query->addField('Town', 'name', 'town');
    $query->addField('Village', 'name', 'village');
    $query->fields('MI');

    if (!empty($form_state['values']['template_id'])) {
        $query->condition('MT.document_template_id', $form_state['values']['template_id'], '=');
    }
    if (!empty($form_state['values']['employee_list'])) {
        $query->condition('MI.author_uid', $form_state['values']['employee_list'], '=');
    }
    //地址级别查询
    _address_search_conditon($query,$form_state);
    if(!user_access('view all document_instance') && user_access('view own document_instance')){
        $query->condition('MT.author_uid',$user->uid,'=');
    }
    if(empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('MI.timestamp', 'DESC');
    }

    $query->limit(variable_get("list_page_item_number", 5));
    $result = $query->orderByHeader($header)->execute();

    $n = 1;
    foreach ($result as $row) {
        if (nonghua_user_access('document_instance', 'delete', $row->document_instance_id, $row->author_uid, 0)) {
            $disabled = ' class="listViewTableCheck" ';
        } else{
            $disabled = ' disabled="true" ';
        }
        $rows[] = array(
            array('data' => '<input type="checkbox"'.$disabled.' value ="' . $row->document_instance_id . '"/>' . $n++, 'class' => ['essential no']),
            array('data' => $row->province . ' '. $row->city . ' '. $row->county . ' '. $row->town . ' '. $row->village, 'class' => ['essential address']),
            array('data' => date("Y-m-d H:i:s", $row->timestamp), 'class' => ['essential timestamp']),
            array('data' => '<a href="' . base_path() . 'document_instance/edit/' . $row->document_template_id . '/' . $row->document_instance_id . '" data-toggle="modal"><img width="20px" height="20px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
        );
    }

    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
    if (sizeof($rows) > 0 && (user_access('delete own document_instance') ||  user_access('delete all document_instance'))) {
        $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
        $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
    }
    $output .= theme('pager');
    return $output;
}

function document_instance_delete()
{
    ajax_table_delete('document_instance', 'document_instance_id');
}
